package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.base.handler.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.OssService;
import com.atguigu.guli.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssProperties ossProperties ;
    String  endpoint ;
    String accessKeyId ;
    String accessKeySecret ;
    String bucketName ;
    @PostConstruct
    public void init() {
        this.endpoint = ossProperties.getEndpoint() ;
        this.accessKeyId = ossProperties.getAccessKeyId() ;
        this.accessKeySecret = ossProperties.getAccessKeySecret() ;
        this.bucketName = ossProperties.getBucketName();
    }
    public String upload(MultipartFile file, String module) {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream() ;
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            String fileName = module+"/" + new DateTime().toString("yyyy/MM/dd/") +
                    UUID.randomUUID().toString().replace("-", "")
                    + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //参数1：保存文件的oss中的桶名 ， 参数2：保存上传文件在桶内的路径和文件名 , 参数3：上传的文件流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //需要手动拼接：
            //https://sh210726leo-guli-file.oss-cn-shanghai.aliyuncs.com/avatar/2021/11/29/9dd94f1ae56c4a52967bce044ffd4a34.jpg
            String path = "https://" + bucketName + ".oss-cn-shanghai.aliyuncs.com/" + fileName;
            return path ;
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR,e) ; //将编译时异常转为运行时异常交给全局异常处理器处理
        }
    }

    @Override
    public void delete(String path, String module) {
        String objectName = path.substring(path.lastIndexOf(module+"/")) ;
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret) ;
        //deleteObject(String bucketName, String key)
        ossClient.deleteObject(bucketName,objectName);
        ossClient.shutdown();
    }
}
